package com.dixon.worddayday.config.security;

import com.dixon.worddayday.bo.CustomerSession;
import com.dixon.worddayday.dao.CustomerRepository;
import com.dixon.worddayday.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private CustomerRepository customerRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if("admin".equals(username)) {
//            return User.builder().username(username).password(new BCryptPasswordEncoder().encode("admin123")).roles("admin")
////                    .authorities("/h2-console", "/h2-console/login", "/api/progress")
//                    .build();

            Customer customer = new Customer(0);
            customer.setName(username);
            customer.setPassword(new BCryptPasswordEncoder().encode("admin123"));
            return new CustomerSession(customer, "admin");
        }

        Customer customer = customerRepository.findByName(username);

        if (customer != null) {
            return new CustomerSession(customer);
        } else {
            throw new UsernameNotFoundException("User not found");
        }
    }
}
